package com.seven.webhook.model.bean.alertBean;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.yaml.snakeyaml.Yaml;

import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;

/**
 * 通知组
 * 转换yaml方便
 */
@Data
@Log4j2
public class AlertGroup {

    private List<RuleGroups> groups;

    public static void main(String[] args) {
        AlertGroup alertGroup = loadYamlFile(FileUtil.getReader("C:/Users/T470/Desktop/test.yml", "UTF-8"));
        System.out.println(JSONUtil.toJsonStr(alertGroup.getGroups().get(1).getRules().get(0)));
    }

    public static AlertGroup loadYamlFile(Reader yamlFileReader) {
        Yaml yaml = new Yaml();
        try {
            HashMap<String, Object> hashMap = yaml.load(yamlFileReader);
            String replace = JSONUtil.toJsonStr(hashMap).replace("for", "forTime");
            return JSONUtil.toBean(replace, AlertGroup.class);
        } catch (Exception e) {
            log.error("exception msg:" + e.getMessage() + "| load yaml error");
            throw e;
        }
    }

    public boolean dumpYamlFile(Writer writer) {
        String replace = JSONUtil.toJsonStr(this).replace("forTime", "for");
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONUtil.parseObj(replace);
        } catch (Exception e) {
            log.error("exception msg:" + e.getMessage() + "| json parse error " + this);
            return false;
        }
        Yaml yaml = new Yaml();
        try {
            yaml.dump(jsonObject, writer);
            return true;
        } catch (Exception e) {
            log.error("exception msg:" + e.getMessage() + "| dump yaml error [ dump object info ->" + jsonObject + " ]");
            return false;
        }
    }
}
